package com.imut.lagain.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.MoodStealRecord;
import com.imut.lagain.service.IMoodStealRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 心情偷取记录控制器
 */
@RestController

@RequiredArgsConstructor
public class MoodStealRecordController {
    private static final Logger log = LoggerFactory.getLogger(MoodStealRecordController.class);

    private final IMoodStealRecordService moodStealRecordService;
    
    /**
     * 创建心情偷取记录
     * @param moodStealRecord 心情偷取记录信息
     * @return 创建结果
     */
    @PostMapping("/mood-steal-records")
    public ResponseEntity<Map<String, Object>> createMoodStealRecord(@RequestBody MoodStealRecord moodStealRecord) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            moodStealRecord.setCreateTime(LocalDateTime.now());
            moodStealRecord.setStealTime(LocalDateTime.now());
            boolean success = moodStealRecordService.save(moodStealRecord);
            
            if (success) {
                response.put("success", true);
                response.put("message", "心情偷取记录创建成功");
                response.put("data", moodStealRecord);
            } else {
                response.put("success", false);
                response.put("message", "心情偷取记录创建失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建心情偷取记录失败", e);
            response.put("success", false);
            response.put("message", "创建心情偷取记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 更新心情偷取记录
     * @param id 心情偷取记录ID
     * @param moodStealRecord 心情偷取记录信息
     * @return 更新结果
     */
    @PutMapping("/mood-steal-records/{id}")
    public ResponseEntity<Map<String, Object>> updateMoodStealRecord(@PathVariable Long id, @RequestBody MoodStealRecord moodStealRecord) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            MoodStealRecord existing = moodStealRecordService.getById(id);
            if (existing == null) {
                response.put("success", false);
                response.put("message", "心情偷取记录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            moodStealRecord.setId(id);
            moodStealRecord.setCreateTime(existing.getCreateTime());
            boolean success = moodStealRecordService.updateById(moodStealRecord);
            
            if (success) {
                response.put("success", true);
                response.put("message", "心情偷取记录更新成功");
                response.put("data", moodStealRecord);
            } else {
                response.put("success", false);
                response.put("message", "心情偷取记录更新失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新心情偷取记录失败", e);
            response.put("success", false);
            response.put("message", "更新心情偷取记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 删除心情偷取记录
     * @param id 心情偷取记录ID
     * @return 删除结果
     */
    @DeleteMapping("/mood-steal-records/{id}")
    public ResponseEntity<Map<String, Object>> deleteMoodStealRecord(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            MoodStealRecord existing = moodStealRecordService.getById(id);
            if (existing == null) {
                response.put("success", false);
                response.put("message", "心情偷取记录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            boolean success = moodStealRecordService.removeById(id);
            
            if (success) {
                response.put("success", true);
                response.put("message", "心情偷取记录删除成功");
            } else {
                response.put("success", false);
                response.put("message", "心情偷取记录删除失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除心情偷取记录失败", e);
            response.put("success", false);
            response.put("message", "删除心情偷取记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取心情偷取记录详情
     * @param id 心情偷取记录ID
     * @return 心情偷取记录信息
     */
    @GetMapping("/mood-steal-records/{id}")
    public ResponseEntity<Map<String, Object>> getMoodStealRecord(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            MoodStealRecord moodStealRecord = moodStealRecordService.getById(id);
            if (moodStealRecord == null) {
                response.put("success", false);
                response.put("message", "心情偷取记录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            response.put("success", true);
            response.put("message", "获取心情偷取记录成功");
            response.put("data", moodStealRecord);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取心情偷取记录失败", e);
            response.put("success", false);
            response.put("message", "获取心情偷取记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 分页查询心情偷取记录列表
     * @param page 页码
     * @param size 每页大小
     * @param thiefUserId 偷取者ID（可选）
     * @param victimUserId 被偷者ID（可选）
     * @param thiefId 小偷ID（可选）
     * @param entryId 条目ID（可选）
     * @return 心情偷取记录列表
     */
    @GetMapping("/mood-steal-records")
    public ResponseEntity<Map<String, Object>> getMoodStealRecordList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long thiefUserId,
            @RequestParam(required = false) Long victimUserId,
            @RequestParam(required = false) Long thiefId,
            @RequestParam(required = false) Long entryId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Page<MoodStealRecord> pageRequest = new Page<>(page, size);
            IPage<MoodStealRecord> moodStealRecordPage;
            
            if (thiefUserId != null) {
                moodStealRecordPage = moodStealRecordService.findByThiefUserId(thiefUserId, pageRequest);
            } else if (victimUserId != null) {
                moodStealRecordPage = moodStealRecordService.findByVictimUserId(victimUserId, pageRequest);
            } else if (thiefId != null) {
                moodStealRecordPage = moodStealRecordService.findByThiefId(thiefId, pageRequest);
            } else if (entryId != null) {
                java.util.List<MoodStealRecord> records = moodStealRecordService.findByEntryId(entryId);
                int fromIndex = (page - 1) * size;
                int toIndex = Math.min(fromIndex + size, records.size());
                java.util.List<MoodStealRecord> pageRecords = records.subList(fromIndex, toIndex);
                
                Page<MoodStealRecord> resultPage = new Page<>(page, size);
                resultPage.setRecords(pageRecords);
                resultPage.setTotal(records.size());
                moodStealRecordPage = resultPage;
            } else {
                moodStealRecordPage = moodStealRecordService.page(pageRequest);
            }
            
            response.put("success", true);
            response.put("message", "获取心情偷取记录列表成功");
            response.put("data", moodStealRecordPage);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取心情偷取记录列表失败", e);
            response.put("success", false);
            response.put("message", "获取心情偷取记录列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}

